﻿(function($) {
	var isLS = typeof window.localStorage !== 'undefined';
	
	if (typeof String.prototype.startsWith != 'function') {
		String.prototype.startsWith = function (str) {
			return this.indexOf(str) == 0;
		};
	}

	//if (typeof String.prototype.trim != 'function') {
		String.prototype.trim = function(regex) {
			if (regex == null)
				regex = '\s';
			var regEx = new RegExp('^' + regex + '+|' + regex + '+$', 'g');
			return this.replace(regEx, '');
		};
	//}

	function get(key) {
		var array = getArray(key);
		var result = null;

		var keyLength = key.length;
		for (var i = 0; i < array.length; i++) {
			var currentKey = array[i];
			var keySubString = currentKey.substring(keyLength);
			if (keySubString.trim(objDelivery) == '' && array.length == 1)
				result = localStorage[currentKey];
			else
				addProperty(result, keySubString, localStorage[currentKey]);
		}
		return result;
	}

	function addProperty(obj, prop, value) {
		prop = prop.trim(objDelivery);
		if (prop == '') {
			return obj;
		}

		var props = prop.split(objDelivery);
		
		if (props.length == 1) {
			obj[props[0]] = value;
		} else {
			var key = '';
			for (var i = 1; i < props.length; i++) {
				key += (props[i] + objDelivery);
			}
			obj[props[0]] = addProperty({}, key, value);
		}

		return obj;
	}
	
	function remove(key) {
		var array = getArray(key);
		for (var i = 0; i < array.length; i++) {
			delete localStorage[array[i]];
		}
	}

	function getArray(key) {
		var result = [];
		var i;
		for (i = 0; i <= localStorage.length - 1; i++) {
			var lsKey = localStorage.key(i);

			if (lsKey == key || lsKey.startsWith(key + objDelivery)) {
				result.push(lsKey);
			}
		}
		return result;
	}

	function set(key, value) {
		if (typeof key === "string" && typeof value === "string") {
			localStorage[key] = value;
			return true;
		} else if (typeof key === "object") {
			getPair(key);
			return true;
		}
		return false;
	}

	function getPair(obj, prefix) {
		if (prefix == null)
			prefix = '';
		
		var key;
		for (key in obj) {
			var currentPrefix = prefix + key;
			if (obj.hasOwnProperty(key)) {
				if (typeof obj[key] !== "object") {
					localStorage[currentPrefix] = '' + obj[key];
				} else {
					getPair(obj[key], currentPrefix + objDelivery);
				}
			}
		}
	}

	var objDelivery = '`';

	/**
	* $.SmarlyStorage.set("name", "value")
	* $.SmarlyStorage.set({"name1":"value1", "name2":"value2"})
	* $.SmarlyStorage.get("name")
	* $.SmarlyStorage.remove("name")
	*/
	$.extend({
		SmarlyStorage: {
			set: isLS ? set : null,
			get: isLS ? get : null,
			remove: isLS ? remove : null,
			isLs: isLS,
		}
	});
})(jQuery);